<template>
  <div class="app-container">
    <el-form style="text-align: left" :model="queryParams" ref="queryForm" :inline="true" :rules="rules" v-show="showSearch" label-width="88px">
      <el-form-item label="版本名称" prop="versionName">
        <el-input
          v-model="queryParams.versionName"
          placeholder="请输入版本名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="版本号" prop="versionCode">
        <el-input
          v-model="queryParams.versionCode"
          placeholder="请输入版本号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="editionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="版本名称" align="center" prop="versionName" />
      <el-table-column label="下载地址" align="center" prop="url" />
      <el-table-column label="版本号" align="center" prop="versionCode" />
      <el-table-column label="版本描述" align="center" prop="description" />
      <el-table-column label="发布人" align="center" prop="createUser" />
      <el-table-column label="发布时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改版本管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="版本名称" prop="versionName">
          <el-input v-model="form.versionName" placeholder="请输入版本名称" />
        </el-form-item>
        <el-form-item label="版本号" prop="versionCode">
          <el-input v-model="form.versionCode" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="版本描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="版本描述" prop="description">
          <el-upload
            class="upload-demo"
            action=''
            :before-upload="beforeUploadVideo"
            :on-remove="handleVODRemove"
            :http-request="hadhttprequest"
            multiple
           :limit="1"
           :file-list="ruleForm.video">
          <el-button v-if="butstate==0" size="small" type="primary">点击上传 <i class="el-icon-upload el-icon--right"></i></el-button>
          <el-button v-else-if="butstate==1" slot="tip" type="info" :loading="true" disabled>apk正在向服务器上传请稍等...</el-button>
          <el-button v-else-if="butstate==2" slot="tip" type="success"  disabled>已存在apk，请删除原先apk在进行上传！</el-button>
          <div slot="tip" class="el-upload__tip">请保证apk格式正确，且不超过1G</div>
          </el-upload>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//import { listEdition, getEdition, delEdition, addEdition, updateEdition, exportEdition } from "@/utils/edition";
import Cookies from "js-cookie";
import OSS from 'ali-oss';
export default {
  name: "Edition",
  components: {
  },
  data() {
    return {
      // 遮罩层
      ruleForm: {
        name: '',
        sort:'',
        introduction:'',
        cover_img: [],
        video:[],
      },
      butstate:0,
      url: this.$Config.url,
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 版本管理表格数据
      editionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        versionName: null,
        versionCode: null,
        description: null,
        createUser: null
      },
      // 表单参数
      form: {
        url:''
      },
      // 表单校验
      rules: {
        versionName: [
          { required: true, message: "请输入版本名称", trigger: "blur" },
        ],
        versionCode: [{ required: true, message: "请输入版本号", trigger: "blur" }],
        unit: [{ required: true, message: "请输入餐品单位", trigger: "blur" }],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询版本管理列表 */
    getList() {
      const that = this;
      that.loading = true;
      this.$axios
        .post(
          that.url + "/admin/edition/list",
          that.$qs.stringify(this.queryParams),
          {
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          }
        )
        .then(function(res) {
          if (res.data.code == 200) {
            console.log(res.data)
            that.editionList = res.data.data;
            that.total = 1;
            that.loading = false;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });

    },
    // 取消按钮
    cancel() {

      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        versionName: null,
        versionCode: null,
        description: null,
        createUser: null
      };
      //this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      //this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加版本管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const that = this;
      that.reset();
      that.open = true;
      const id = row.id || that.ids

      this.$axios
        .get(
          that.url + '/admin/edition/edit/'+id,
          {
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          }
        )
        .then(function(res) {
          if (res.data.code == 200) {
            that.form = res.data.data;
            that.open = true;
            that.title = "修改版本管理";
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });

      getEdition(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改版本管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      const that = this;
      if(that.form.url == '' || that.form.url==undefined){
        that.$message({
          message: '请上传apk',
          type: "warning"
        });
        return false;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          let url = '/admin/edition/add'
          if (that.form.id != null) {
            url = '/admin/edition/edit'
          }
          this.$axios
            .post(
              that.url + url,
              that.$qs.stringify(that.form),
              {
                headers: {
                  "x-baie-admin-token": Cookies.get("token")
                }
              }
            )
            .then(function(res) {
              if (res.data.code == 200) {
                that.getList();
                that.open = false;
              } else {
                that.$message({
                  message: res.data.msg,
                  type: "warning"
                });
              }
            })
            .catch(function(error) {
              console.log(error);
            });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {

      let that = this;
      const ids = row.id || this.ids.toString();
      debugger
      this.$confirm('是否确认删除版本管理编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        that.delEdition(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    delEdition(ids){
      let that = this;
      this.$axios
        .post(
          that.url + '/admin/edition/delete',
          that.$qs.stringify({ids:ids}),
          {
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          }
        )
        .then(function(res) {
          if (res.data.code == 200) {
            that.getList();
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      // const queryParams = this.queryParams;
      // this.$confirm('是否确认导出所有版本管理数据项?', "警告", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning"
      // }).then(function() {
      //   return exportEdition(queryParams);
      // }).then(response => {
      //   this.download(response.msg);
      // })
    },
    beforeUploadVideo(file) {
      const isLt1G = file.size / 1024 / 1024 < 1024;
      console.log(file)
      if (file.name.indexOf('.apk') == -1) {
        this.$message.error('请正确上传apk格式');
        return false;
      };
      if (!isLt1G) {
        this.$message.error('不能超过1G哦!');
        return false;
      };
      this.butstate=1;//项目需要
    },
//文件删除
    handleVODRemove(file, fileList) {
      this.ruleForm.video = fileList;
      this.butstate=0;
    },
//直接向阿里云上传阿里云
    async getOssToken(content){
      let that = this;
      // 上传到阿里云视频文件路径名称，你个人爱好，谁也阻挡不聊你，不要用中文，你硬要...
      let videoName = 'edition/'+Date.parse(new Date())/1000+content.file.name;
      //我的是用文件夹名+用户id+时间戳文件名，不要问为什么，我喜欢！
      let client = new OSS({
        region: 'oss-cn-beijing',
        accessKeyId: 'LTAI4Fj6pVZZ1czb6MvDwZx6',
        accessKeySecret: 'wNsd05ImRahtdFEJBRIJkUMqwbgzV0',
        bucket:'eschoolweb',
        secure:true
      });
      //贞子判断
      try {
        //multipartUpload这个什么意思看文档，我只告诉你用来直接访问oss
        let result = await client.multipartUpload(videoName , content.file, {
          progress: async function (p) {//这是上传进度条
            content.onProgress({percent: parseInt(p * 100)+'%', returnValue: true });
            if (p==1) {
              that.butstate=2;
            };
          }
        });
        that.form.url = result.res.requestUrls[0].split("?")[0];

      } catch (e) {
        console.log('失败',e)
        if (e.code === 'ConnectionTimeoutError') {
          content.onError('apk上传超时')
          throw "apk上传超时!";
        }else{
          content.onError('apk上传失败')
        }
      }
    },
// 视频自定义上传访问授权
    async hadhttprequest(content){
      //这里是用来调用接口请求获取服务端返回阿里云oss验证参数，简单的说问后台那吊毛要接口就可以了！
      let that=this;
      let res = that.getOssToken(content);
    }
  }
};
</script>
